<?php
namespace Statistics\Lib;

/**
 * 自动签名
 *
 * PHP version 5
 *
 * @package   AutoPack
 * @author Giles <giles.wang@icloud.com>
 * @version V1.1
 */

class AutoPack
{

    //打包类型
    protected $type = '2'; //1 为自动单个打包 2 自动批量打包(批量打包要保证包的名字和配置文件名字一致否则打包会失败)
    protected $packType = '1'; //1 i苹果包  2 游戏包
    protected $packName = ''; //批量打i苹果包的时候提供
    protected $confName = ''; //配置文件名字 批量打包的时候不必提供
    protected $dir = '';
    protected $channelId  = '1001000101';
    protected $certificate = 'iPhone Developer: Zhibin Wang (7R28ZQL59M)';
    protected $jpush = array();
    protected $path = '/Users/Giles/workspace/workCodes/socket/Applications/AutoPack';

    function __construct()
    {

    }

    /**
     * 解析配置文件
     * @author Giles <giles.wang@iclode>
     * @return array
     *
     */
    function analysis()
    {
        if(empty($this->confName)){
            die("配置文件载入失败");
        }

        exec("security cms -D -i ". $this->path. 'old/'. $this->confName ." > $this->path .'temp.xml");

        $return = array();
        $xmlData = simplexml_load_file($this->path.'temp.xml');
        $string = (array) $xmlData->dict->string;
        if($this->channelId == '3001000101') {
            $return['certificate'] = $this->certificate;
        }else {
            $return['certificate'] = 'iPhone Distribution: '.$string[2];
        }

        $bundleTemp = (array) $xmlData->dict->dict->string;
        $bundlitem = $bundleTemp[0];
        $temp = explode('.', $bundlitem);
        $return['itermid'] = $temp[0];
        unset($temp[0]);
        $return['bundleId'] = implode('.', $temp);
        if(empty($return['bundleId'])) {
            $bundlitem = $bundleTemp[2];
            $temp = explode('.', $bundlitem);
            $return['itermid'] = $temp[0];
            unset($temp[0]);
            $return['bundleId'] = implode('.', $temp);
        }
        $return['certificatemd5'] = md5($return['certificate']);

        if($this->packType == 1) {
            $jpush = $this->jpush();
            $return['jpushappkey'] = isset($jpush[$return['bundleId']]) ? $jpush[$return['bundleId']] : '';
        }
        return $return;
    }


    /**
     * 执行打包程序
     *
     * @author Giles <giles.wang@icloud.com>
     * @return Void
     *
     */
    function  run()
    {
        if($this->packType == 1) {
            $files = glob($this->path. 'old/*.mobileprovision');
            foreach($files as $file) {
                $fileTemp = explode('/', $file);
                $this->confName = $fileTemp[1];
                if(!is_file($this->path. 'old/'.$this->confName)) {
                    exit($this->confName .'的配置文件不存在！');
                }

                $config = $this->analysis();
                $this->pack($config);
            }
        }else {
            $files = glob($this->path. 'old/*.ipa');
            foreach($files as $file) {
                $fileTemp = explode('/', $file);
                $this->packName = $fileTemp[1];
                $confTemp = explode('.', $this->packName);
                $this->confName = $confTemp[0] .'.mobileprovision';
                if(!is_file($this->path. 'old/'.$this->confName)) {
                    exit("包:". $this->packName .'的配置文件不存在！');
                }

                $config = $this->analysis();
                $this->pack($config);
            }
        }
    }

    function pack($config)
    {
        echo $this->packName." --开始打包\n";
        exec("unzip -q ".$this->path. "old/". $this->packName);
        exec("chmod -R 777 $this->path. 'Payload");
        exec("chmod 777 $this->path. 'temp.entitlements");

        $dirs = $this->getDir($this->path.'Payload');

        if($config['bundleId'] == '*') {
            $actionsss = '/usr/libexec/plistbuddy -c "Print CFBundleIdentifier" '.$dirs .'Info.plist';
            exec($actionsss, $actions, $cobak);
            $config['bundleId'] = $actions[0];
        }
        exec("cp ". $this->path.'old/'. $this->confName." ".$dirs ."embedded.mobileprovision");
        //下面这行注释了就是不改bundle id
        exec("/usr/libexec/plistbuddy -c 'Set :CFBundleIdentifier \"". $config['bundleId'] ."\"'  ".$dirs ."Info.plist");
        $isAdd = "/usr/libexec/plistbuddy -c 'Add :CerBundleID String \"". $config['certificatemd5'] ."|".$this->channelId."\"' ". $dirs ."Info.plist";
        exec($isAdd, $actions, $cobak);
        if($cobak != 0) {
            echo "使用Add失败，尝试用Set 忽略Add报错信息\n";
            $set = "/usr/libexec/plistbuddy -c 'Set :CerBundleID \"". $config['certificatemd5'] ."|".$this->channelId."\"' ". $dirs ."Info.plist";
            exec($set);
        }
        //exec("/usr/libexec/plistbuddy -c 'Set :CerBundleID \"". $config['certificatemd5'] ."|".$this->channelId."\"' ". $dirs ."Info.plist");
        if ($this->packType == 1) {
            exec("/usr/libexec/plistbuddy -c 'Set :APP_KEY \"". $config['jpushappkey'] ."\"' ". $dirs ."PushConfig.plist");
        }
        exec("/usr/libexec/plistbuddy -c 'Set :application-identifier \"". $config['itermid'] .".". $config['bundleId'] ."\"' ".$this->path."temp.entitlements");
        exec("/usr/libexec/plistbuddy -c 'Set :com.apple.developer.team-identifier \"". $config['itermid'] ."\"' ".$this->path."temp.entitlements");
        exec("/usr/libexec/plistbuddy -c 'Set :keychain-access-groups:0 \"". $config['itermid'] .".*\"' ".$this->path."temp.entitlements");
        $cuk = $config['certificate'];

        $action = "/usr/bin/codesign --preserve-metadata=identifier,entitlements -f -s \"".  $cuk ."\" --identifier \"". $config['bundleId'] ."\" --entitlements ".$this->path."temp.entitlements ". $dirs;
        exec($action, $actions, $cobak);
        if($cobak != 0){
            exec('rm -rf '.$this->path.'Payload');
            echo $this->packName ."签名失败\n";
            return;
        };
        exec("zip -r -q temp.ipa ".$this->path."Payload/");
        if($this->packType == 1) {
            $newFile = $config['bundleId'];
        } else {
            $newFile = rtrim($this->getPackName($this->packName));
        }

        rename('temp.ipa', $this->path.'new/'. $newFile .'-'.date('md').'-'.$this->channelId.'.ipa');
        exec('rm -rf '.$this->path.'Payload');
        echo $this->packName.' --打包完成！';
    }

    /**
     *   获取包的名字
     */
    function getPackName($packs){
        $temp  = explode('.', $packs);
        return $temp[0];
    }

    /**
     * 获取解压后的包路径
     */
    function getDir($dir) {
        $dirArray[]=NULL;
        //echo $dir;
        if (false != ($handle = opendir ($dir))) {
            $i=0;
            while ( false !== ($file = readdir($handle))) {
                //去掉"“.”、“..”以及带“.xxx”后缀的文件
                //var_dump($file);
                if (strpos($file, '.app')) {
                    $dirArray[$i]=$file;
                    $i++;
                }
            }
            //关闭句柄
            closedir ($handle);
        }
        $lastDir = $dir . '/'. $dirArray[0].'/';
        if(strpos($lastDir, ' ')) {
            $lastDir = str_replace(' ', '\ ', $lastDir);
        }
        return $lastDir;
    }

    function jpush()
    {
        return array(
            "com.dongtang.helper"=> "3e9203b33c474288e292f2b5",
            "com.gaoke.helper"=> "f32486e7fc7a3644c596c2d8",
            "com.sf.helper"=> "bb4ef618a977e0bac7dd203b",
            "com.metal.helper"=> "17311c0c216f0231677d3fa5",
            "com.derui.helper"=> "b685e339fc27b1170a805403",
            "com.baiyun.helper"=> "7b69cc65969996cccad09ad2",
            "com.wugu.helper"=> "66ccbb9629a6a9aa041cd816",
            "com.suzhong.helper"=> "e23d74f00e102a9614c03179",
            "com.newland.helper"=> "1fa0be7417e11a7d37f582ee",
            "com.huihua.helper"=> "c03f6a7f6b24d6c36da7fd3c",
            "com.FeriaDigital.helper"=> "b781a63dec9aa6202dd3ffa1",
            "com.GuangzhouBomeng.helper"=> "3f783ed25a5bb004aaeffef0",
            "com.KUNMINGYUNNEIPOWER.helper"=> "088520f11a381647f0524df9",
            "com.GoldenBright.helper"=> "1866225df69e9079b2822e93",
            "com.Looyet.helper"=> "09dfc0972177df71621cb7fe",
            "com.PharmaLab.helper"=> "89ce53b76be94ae94f9f0306",
            "com.Catalyst.helper"=> "39ec81e08d34421d41022e13",
            "com.Eventplus.helper"=> "38489f7368708024a4faa9be",
            "com.Column.helper"=> "d5a25beeeadc933fc7a8865f",
            "com.DeKong.helper"=> "1b85e8074b3cfef6ed34a707",
            "com.Heavy.helper"=> "57453ecbd6321f3b050a6f5b",
            "com.Fable.helper"=> "ceb549c6568da6912d626bdf",
            "com.CardCity.helper"=> "f707465ec4a71aded6bfc525",
            "com.Coninst.helper"=> "fb2980f3e2a721a4bb6ef1c2",
            "com.Linvison.helper"=> "555ac2e92db3ee6c234801f7",
            "com.ShuangFei.helper"=> "01ff8cc308cad5cec9533cdc",
            "com.Longjie.helper"=> "71d3e9da235c6b4272f234b0",
            "com.Jiaming.helper"=> "5b3da862bb4a72a5822b138d",
            "com.Shengfuli.helper"=> "0d357a8a4b23f02d41e4e3c8",
            "com.Guobang.helper"=> "9c0515352c442d1128fee458",
            "com.Yincheng.helper"=> "44edce971b184ecb3ceb93b3",
            "com.Yuebo.helper"=> "0da5335024a0414c48b7471a",
            "com.Kerulen.helper"=> "18681f28529617eae51d548e",
            "com.Zhongde.helper"=> "46ce3b178fa8bf0592219179",
            "com.Panasign.helper"=> "458bce48d45b244cccc98a89",
            "com.AOKMAN.helper"=> "8811c11c2f3c7a4c1a4d4a8d",
            "com.Fangsheng.helper"=> "de58537ad1c3780146f6ddb3",
            "com.Jingxuan.helper"=> "d7a7ca7a10117c951920d3c0",
            "com.Qitongbao.helper"=> "0f17007c48263a3df1fff7e4",
            "com.Wanqu.helper"=> "39e038a8204c9e876cf32d26",
            "com.JieDaXing.helper"=> "b8c52bffcb03a97c83bd5d83",
            "com.Aromas.helper"=> "68bb0130b9340bf13f1dd8fc",
            "com.Yongbang.helper"=> "fa33f0abcfb977245e6f2b1a"
        );

    }

}